Spring - 无法在自定义 ClientHttpRequestInterceptor 实现中记录请求主体 class

Spring - unable to log request body in custom ClientHttpRequestInterceptor implementation class

我创建了一个 class 名称 HttpInterceptor,它实现了 ClientHttpRequestInterceptor。此 class 的目的是拦截 resttemplate 调用,然后覆盖拦截方法。在执行期间,我无法记录请求正文。但是有一个request body是前端发来的

@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {

    String requestBody = "";
    String url = request.getURI().toString();

    ClientHttpResponse response = null;
    Date timeIn = new Date();
    String responseBody = "";

    // I have also try new String(body, "UTF-8") and many others.
    requestBody = new String(body, Charset.forName("UTF-8"));

    logger.info("=============================REQUEST BEGIN==============================================");
    logger.info("URI         :" + url);
    logger.info("Method      :" + request.getMethod());
    logger.info("Headers     :" + request.getHeaders());
    logger.info("Request body:" + requestBody);
    logger.info("=============================REQUEST END================================================");

    response = execution.execute(request, body);

    responseBody = StreamUtils.copyToString(response.getBody(), Charset.defaultCharset());
        //new String(ByteStreams.toByteArray(response.getBody()), Charset.forName("UTF-8"))

    logger.info("=============================RESPONSE BEGIN=============================================");
    logger.info("Status code  : " + response.getStatusCode());
    logger.info("Status text  : " + response.getStatusText());
    logger.info("Headers      : " + response.getHeaders());
    logger.info("Response body: " + responseBody);
    logger.info("=============================RESPONSE END===============================================");

    return response;
}

其余模板初始化如下:

RestTemplate restTemplate = new RestTemplate(
                new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()));

restTemplate.setInterceptors(Collections
            .singletonList(new HttpInterceptor()));

我还在 Whosebug 上发现了类似的问题 为什么我的自定义 ClientHttpRequestInterceptor 响应为空 ,但是和我想要的完全不一样

这似乎是一个非常有趣的解决方案,但甚至不知道它是如何实现的。事实上,我很难记录请求正文,但找到了一个解决方案,在该解决方案中,我必须通过对 RestTemplate 初始化进行一次更改来构建完整的解决方案,然后恢复并再次构建解决方案,这解决了我的问题。以下是变化:

在没有此行的情况下构建完整的解决方案 new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory())

RestTemplate restTemplate = new RestTemplate();

restTemplate.setInterceptors(Collections
            .singletonList(new HttpInterceptor()));

然后像这样恢复到最初的状态,然后构建解决方案解决了我的问题:

RestTemplate restTemplate = new RestTemplate(
                new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()));

restTemplate.setInterceptors(Collections
            .singletonList(new HttpInterceptor()));

注意:我已经用不同的输入(即请求)测试了解决方案,它运行正常。